package com.chant.startFarming.utils;

import com.chant.startFarming.dto.UserDTO;
import com.chant.startFarming.entity.Users;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PermissionCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从ThreadLocal中获取用户信息
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            response.getWriter().write("未登录");
            return false;
        }

        // 如果是HandlerMethod，检查是否有权限注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PermissionCheck permissionCheck = handlerMethod.getMethodAnnotation(PermissionCheck.class);
            if (permissionCheck != null) {
                int requiredRole = permissionCheck.value();
                if (user.getRole() != requiredRole) {
                    response.getWriter().write("权限不足");
                    return false;
                }
            }
        }

        return true;
    }
}